
package DAO;

import Utils.HibernateUtil;
import java.util.List;
import javax.faces.model.SelectItem;
import model.Metric;
import org.hibernate.Session;
import org.hibernate.Transaction;
import DAO.MetricaDao;
import java.sql.SQLException;
import java.util.Iterator;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import javax.persistence.PersistenceException;
import javax.servlet.http.HttpSession;
import model.Category;
import model.User;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import validator.e;

public class MetricDaoImp implements MetricaDao{
 e er = new e();
 
 @Override
 public void save(Metric metric){
     Session session = HibernateUtil.getSessionFactory().openSession(); 
     Transaction t = session.beginTransaction();
     
     if(consultMetric(metric.getName())){
     try{
         session.save(metric);
         t.commit();
         e.exibirMsgSucesso("Sucess");
     }catch(HibernateException err){
         e.exibirMsgErro("Error - Try Again");
     }}else{
         e.exibirMsgErro("Duplicate Name");
     }
     session.close();
 }
 
 public Metric getMetrica(int id){
     Session session = HibernateUtil.getSessionFactory().openSession();
     Metric metrica = (Metric) session.load(Metric.class, id);
     session.close();
     return metrica;
 }
 
 public List<Metric> list(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        Query query= session.createSQLQuery("select * from Metric ").addEntity(Metric.class);
        List lista = query.list();
        session.close();
        return lista;
        }
 
public void remove(Metric metric) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        session.delete(metric);
        t.commit();
        session.close();
    }

public void update(Metric metric) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        try{
            session.update(metric);
            t.commit();
            e.exibirMsgSucesso("Sucess");
        }
        catch(HibernateException err){
            e.exibirMsgErro("Error");
        }
        session.close();
    }

public boolean consultMetric(String name){
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction t = session.beginTransaction();
        Query query= session.createSQLQuery("select * from Metric where name = :name").addEntity(Metric.class);
        query.setParameter("name",name);
        List lista = query.list();
        if(lista == null || lista.isEmpty()){
            return true;
        }else{
            return false;
        }
}
  
    
}
